<?php

namespace app\mp\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Vod\Vod;
use app\common\entity\BackResult;
use app\common\entity\Result;
use app\common\model\UserFavorWord;
use app\common\model\VideoList;
use app\common\model\VideoNote;
use app\common\model\VideoWord;
use app\common\service\OrderService;
use app\common\service\StudyPlanService;
use app\common\service\TopicService;
use app\common\service\UserService;
use app\common\service\VideoAndTopicService;
use app\common\youdao\Assess;
use app\Request;
use app\common\service\VideoService;
use app\wxapp\service\VideoService as WxAppVideoService;
use think\facade\Db;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/6 0006
 * Time: 16:59
 */
class Video extends Base
{
    private $regionId = 'cn-shanghai';
    /**
     * 专栏类型
     * @var int
     */
    private $topicType = 2;

    public function videoInfo(Request $request)
    {
        $id = $request->param('id');
        $video = Db::table('video_list')->where(['id' => $id])->find();
        if (!$video) {
            BackResult::error(['type' => 'empty']);
        }

        $vip = UserService::getVipInfo($this->user['id']);

        if ($video['topic_id'] > 0) {
            // 视频属于专栏时，查询是否已添加学习计划
            $planed = StudyPlanService::get($video['topic_id'], 2, $this->user['id']);
            // 收费视频
            if (!$video['is_free']) {
                // 没有添加学习计划不可看
                if (!$planed) {
                    return BackResult::error(['type' => 'topic', 'id' => $video['topic_id'], 'action' => 'add']);
                }
                // 不是VIP且没有购买的不可看
                if (!$vip && 0 === (int)$planed['order_id']) {
                    return BackResult::error(['type' => 'topic', 'id' => $video['topic_id'], 'action' => 'buy']);
                }
            }

        } else {
            // 是否有购买视频
            $planed = StudyPlanService::get($video['id'], 1, $this->user['id']);
            if ($video['fee'] > 0.00 && (!$planed || 0 === (int)$planed['order_id'] || !$vip)) {
                // 视频如果是收费的，则需要购买
                return BackResult::error(['type' => 'video', 'id' => $video['id'], 'action' => 'buy', 'fee' => $video['fee']]);
            }
        }

        $accessKeyId = env('aliyun.ali_access_key_id');
        $accessKeySecret = env('aliyun.ali_access_key_secret');
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId($this->regionId)
            ->connectTimeout(1)
            ->timeout(3)
            ->asDefaultClient();

        $result = Vod::v20170321()->getPlayInfo()->withVideoId($video['out_video_id'])
            ->format('JSON')
            ->request();

        return Result::success([
                'VideoBase' => $result['VideoBase'],
                'PlayInfoList' => $result['PlayInfoList'],
                'subtitle_src' => 'https://medical-course.oss-cn-shenzhen.aliyuncs.com/' . $video['subtitle_src'],
                'video' => $video,
                'time' => VideoService::getPlayTime($video['id'], $this->user['id'])
            ]
        );
    }

    /**
     * 用于请求专栏的介绍视频
     * @param Request $request
     * @return \think\Response
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function videoInfoByOutId(Request $request)
    {
        $outId = $request->param("outId");

        $accessKeyId = env('aliyun.ali_access_key_id');
        $accessKeySecret = env('aliyun.ali_access_key_secret');
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId($this->regionId)
            ->connectTimeout(1)
            ->timeout(3)
            ->asDefaultClient();

        $result = Vod::v20170321()->getPlayInfo()->withVideoId($outId)
            ->format("JSON")
            ->request();

        return Result::success([
                'VideoBase' => $result['VideoBase'],
                'PlayInfoList' => $result['PlayInfoList'],
            ]
        );
    }

    public function favor(Request $request)
    {
        $id = $request->param('id');
        $service = new VideoService();
        $service->updateFavor($id, $this->user['id']);
        $result = $service->favorStatus($id, $this->user['id']);
        return Result::success($result);
    }

    /**
     * 获取当前用户是否收藏该视频 和该视频的收藏数量
     * @param Request $request
     * @return mixed
     */
    public function favorStatus(Request $request)
    {
        $videoId = $request->param('id');
        $service = new VideoService();
        $result = $service->favorStatus($videoId, $this->user['id']);
        return Result::success($result);
    }

    /**
     * 分享视频次数
     * @param Request $request
     * @return \think\Response
     */
    public function share(Request $request)
    {
        $id = (int)$request->param('id');
        $videoService = new VideoService();
        if ($video = $videoService->getOne($id)) {
            $video->share++;
            $video->save();
            return Result::success($video->share);
        } else {
            return BackResult::error(null, '参数异常');
        }
    }

    /**
     * 语音测评
     * @param Request $request
     * @return mixed
     */
    public function assess(Request $request)
    {
        $data = $request->post();
        if (empty($data['videoId']) || empty($data['sentenceId']) || empty($data['text'])) {
            return Result::error('缺少参数');
        }

        $videoId = $data['videoId'];
        $sentenceId = $data['sentenceId'];
        $text = $data['text'];

        //去掉标点符号
        $text = preg_replace('/[^a-zA-Z0-9\s]+/', " ", $text);

        $service = new WxAppVideoService();
        $data = $service->assess($videoId, $sentenceId, $this->user['id'], $text);
        return Result::success($data);
    }

    /**
     * 获取语音基本信息 其他人语音数量 自己的读音
     * @param Request $request
     * @return \think\Response
     */
    public function voiceBaseInfo(Request $request)
    {
        $data = $request->param();
        if (empty($data['videoId']) || empty($data['sentenceId'])) {
            return Result::error('缺少参数');
        }

        $videoId = $data['videoId'];
        $sentenceId = $data['sentenceId'];

        $service = new WxAppVideoService();
        $result = $service->voiceBaseInfo($videoId, $sentenceId, $this->user['id']);

        return Result::success($result);
    }

    /**
     * 同学发声列表
     */
    public function voiceList(Request $request)
    {
        $videoId = $request->param('videoId');
        $sentenceId = $request->param('sentenceId');
        $page = $request->param('page', 1);
        $pageSize = $request->param('pageSize', 10);

        $service = new WxAppVideoService();
        $res = $service->voiceList($videoId, $sentenceId, $page, $pageSize);
        return Result::success($res);
    }

    /**
     * 获取视频或者专栏
     * @param Request $request
     * @return \think\Response
     */
    public function getList(Request $request)
    {
        //1 视频 2 专栏
        $type = $request->param('type', 1);
        $page = $request->param('page', 1);
        $pageSize = $request->param('pageSize', 20);
        $categoryId = $request->param('categoryId');
        $keyword = $request->param('keyword', '');
        $where = [];

        if (!empty($categoryId)) {
            array_push($where, [
                'category_id', '=', $categoryId
            ]);
        }
        if (!empty($keyword)) {
            array_push($where, [
                'title', 'like', '%' . $keyword . '%'
            ]);
        }

        if ($type == 1) {
            $service = new VideoService();
            $data = $service->getList($page, $pageSize, $where);
        } else {
            $service = new TopicService();
            $data = $service->getList($page, $pageSize, $where);
        }

        return Result::success($data);
    }

    /**
     * 搜索视频或者专栏  当前只搜视频  因为搜索是混合的  所以办法就是把数据放在一起 用一个表或者 es 来做
     * @param Request $request
     * @return mixed
     */
    public function search(Request $request)
    {
        $page = (int)$request->param('page', 1);
        $keyword = trim($request->param('keyword', ''));
        if (!$keyword) {
            return BackResult::error(null, '请输入搜索关键字');
        }
        $service = new VideoAndTopicService();
        $result = $service->select(['page' => $page, 'keyword' => $keyword, 'order' => 'hot']);
        return Result::success($result);
    }

    /**
     * 获取视频的相关生词
     * 不用分页 每个视频的词汇有限
     * @param Request $request
     * @return \think\Response
     */
    public function words(Request $request)
    {
        $id = $request->param('id');
        if (empty($id)) {
            return BackResult::error(null, '参数异常');
        }
        $service = new VideoService();
        $words = $service->words($id);
        return Result::success($words);
    }

    /**
     * 收藏单词
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function favorWord(Request $request)
    {
        $id = (int)$request->param('id');
        if (!$id || !($word = Db::table("word_dict")->find($id))) {
            return BackResult::error(null, '参数异常');
        }
        $rel = Db::table('video_word')->where('word_id', $id)->find();
        if (!UserFavorWord::where(['word_id' => $id, 'uid' => $this->user['id']])->find()) {
            $favor = new UserFavorWord();
            $favor->uid = $this->user['id'];
            $favor->video_id = $rel['video_id'];
            $favor->word_id = $id;
            $favor->create_time = date('Y-m-d H:i:s');
            if (!$favor->save()) {
                return BackResult::error(null, '数据异常');
            }
        }
        return BackResult::success();
    }


    public function getWordScreen(Request $request)
    {
        $videoId = $request->param('id');
        $service = new VideoService();
        $result = $service->getWordScreenNoPage($videoId);
        return Result::success($result);
    }

    /**
     * 更新视频观看进度
     * @param Request $request
     * @return \think\Response
     */
    public function updateProgress(Request $request)
    {
        $id = (int)$request->param('id');
        $watchTime = (int)$request->param('watchTime');

        if (!$id || $watchTime < 0) {
            return BackResult::error('参数异常');
        }
        $result = VideoService::updateProgress($id, $this->user['id'], $watchTime);
        if (!$result) {
            return BackResult::error('数据异常');
        }
        return BackResult::success();
    }

    /**
     * 获取视频的笔记留言
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNoteList(Request $request)
    {
        $id = (int)$request->param('id');
        $page = (int)$request->param('page');
        $list = !$id ? [] : Db::table('video_note')
            ->alias('vn')
            ->leftJoin('wechat_user u', 'u.id = vn.uid')
            ->where('vn.video_id', $id)
            ->order('id', 'desc')
            ->page($page, 20)
            ->field('vn.id,vn.note,vn.create_time,u.nick_name,u.avatar_url')
            ->select();
        return Result::success($list);
    }

    /**
     * 添加笔记留言
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sendNote(Request $request)
    {
        $id = (int)$request->param('id');
        $note = trim($request->param('note'));
        if (0 === strlen($note)) {
            return BackResult::error(null, '请先输入笔记内容');
        }
        if (!$id || !($video = VideoList::find($id))) {
            return BackResult::error(null, '参数异常');
        }
        if (strlen($note) > 200) {
            $note = mb_substr($note, 0, 200);
        }
        // 更新数据
        $videoNote = new VideoNote();
        $videoNote->video_id = $id;
        $videoNote->uid = $this->user['id'];
        $videoNote->note = $note;
        $videoNote->create_time = date('Y-m-d H:i:s');
        if (!$videoNote->save()) {
            return BackResult::error(null, '数据异常');
        }
        // 更新视频
        $video->favor++;
        $video->save();
        // 清除该视频的笔记缓存（我的空间）
        $cacheKey = "VIDEO_NOTE:{$this->user['id']}:{$id}";
        cache($cacheKey, null);
        return Result::success([
            'id' => $videoNote->id,
            'note' => $videoNote->note,
            'create_time' => $videoNote->create_time,
            'nick_name' => $this->user['nick_name'],
            'avatar_url' => $this->user['avatar_url']
        ]);
    }

    /**
     * 删除笔记留言
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delNote(Request $request)
    {
        $id = (int)$request->param('id');
        if (!$id || !($note = VideoNote::find($id)) || $note->uid != $this->user['id']) {
            return BackResult::error(null, '参数异常');
        }
        if ($note->delete()) {
            // 清除笔记缓存
            $cacheKey = "VIDEO_NOTE:{$this->user['id']}:{$note->video_id}";
            cache($cacheKey, null);
            // 更新视频笔记数
            $video = VideoList::find($note->video_id);
            $video->favor--;
            $video->save();
            return BackResult::success();
        } else {
            return BackResult::error(null, '数据异常');
        }
    }

    /**
     * 删除单词
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delWord(Request $request)
    {
        $id = (int)$request->param('id');
        if (!$id || !($favor = UserFavorWord::find($id)) || $favor->uid != $this->user['id']) {
            return BackResult::error(null, '参数异常');
        }
        if ($favor->delete()) {
            return BackResult::success();
        } else {
            return BackResult::error(null, '数据异常');
        }
    }
}